package com.bigboy.bbs.util;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.bigboy.bbs.entity.User;


public class UserSessionFilter implements Filter {
	private String url = "";
	String[] urls = null;
	public void destroy() {

	}
	public boolean checkUrl(String requrl){
		boolean flag = false;
		for (int i = 0; i < urls.length; i++) {
			if(requrl.equals(urls[i])){
				flag = true;
				break;
			}
		}
		return flag;
	}
	public void doFilter(ServletRequest req, ServletResponse resp,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) resp;
		String requestUrl = request.getRequestURI();
		HttpSession session = request.getSession();
		User user = (User) session.getAttribute("user");
		if(user == null){
			boolean flag = checkUrl(requestUrl);
			if(flag){
				response.sendError(404);
			}else{
				chain.doFilter(req, resp);
			}
		}else{
			chain.doFilter(req, resp);
		}
	}

	public void init(FilterConfig config) throws ServletException {
		String url = config.getInitParameter("url");
		 urls = url.split(",");
		 for (int i = 0; i < urls.length; i++) {
			System.out.println(urls[i]);
		}
	}

}
